import allure
import xml.etree.ElementTree as ET

def Assert(condition,expect_msg,actually_msg):
    """
    自定义的断言函数
    参数：
        condition:断言条件
        expect_msg:预期结果
        actually_msg:实际结果
    """
    if condition:
        step_desc = f'验证通过，预期得到{expect_msg}，实际得到{actually_msg}'
        print(step_desc)
    else:
        step_desc = f'验证失败，预期得到{expect_msg}，实际得到{actually_msg}'
        print(step_desc)

    with allure.step(step_desc):
        if not condition:
            # 断言失败时，抛出详细错误
            assert False, f"{step_desc} → 断言失败"

def Assert_xml(condition,expect_msg,actually_msg):
    """
    自定义的XML文件断言函数
    :param condition: 断言条件
    :param expect_msg: 预期结果
    :param actually_msg: 实际结果
    :return:
    """
        try:
        # 解析XML并提取字段
        root = ET.fromstring(xml_response)
        actual_msg = root.findtext(needed_msg)

        # 清洗实际值
        cleaned_actual = actual_msg.strip() if actual_msg is not None else None

        # 转换为字符串并显示原始值，方便调试
        actual_str = str(cleaned_actual) if cleaned_actual is not None else "None"
        expect_str = str(expect_msg)

        # 处理实际结果描述参数
        if actually_msg is None:
            display_actual = actual_str  # 用清洗后的值显示
        else:
            display_actual = actually_msg

        # 核心断言逻辑
        if actual_str == expect_str:
            step_desc = f'验证通过，预期得到{expect_str}，实际得到{display_actual}'
            print(step_desc)
        else:
            step_desc = f'验证失败，预期得到{expect_str}，实际得到{display_actual}'
            print(step_desc)
            assert False, step_desc  # 只有确实不相等时才断言失败

        with allure.step(step_desc):
            pass

    except ET.ParseError as e:
        step_desc = f'XML解析失败：{str(e)}'
        print(step_desc)
        assert False, step_desc
    except Exception as e:
        # 捕获其他异常时，明确显示错误原因
        step_desc = f'断言过程出错：{str(e)}'
        print(step_desc)
        assert False, step_desc